/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 */
package org.apache.mina.transport.bio;

import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;

import org.apache.mina.api.IoFuture;
import org.apache.mina.api.IoSession;
import org.apache.mina.api.IoSessionConfig;
import org.apache.mina.service.idlechecker.IdleChecker;
import org.apache.mina.session.AbstractIoSession;
import org.apache.mina.session.DefaultWriteRequest;
import org.apache.mina.session.WriteRequest;

/**
 * A {@link IoSession} for {@link BioUdpServer}
 * 
 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
 */
public class BioUdpSession extends AbstractIoSession {

    private SocketAddress remoteAddress;

    public BioUdpSession(SocketAddress remoteAddress, BioUdpServer service, IdleChecker idleChecker) {
        super(service, idleChecker);
        this.remoteAddress = remoteAddress;
    }

    
    /**
     * Set this session status as connected. To be called by the processor selecting/polling this session.
     */
    void setConnected() {
        if (!isCreated()) {
            throw new IllegalStateException("Trying to open a non created session");
        }

        state = SessionState.CONNECTED;
        processSessionOpen();
    }


    /**
     * {@inheritDoc}
     */
    @Override
    public SocketAddress getRemoteAddress() {
        return remoteAddress;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SocketAddress getLocalAddress() {
        return ((BioUdpServer) getService()).getBoundAddress();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public IoFuture<Void> close(boolean immediately) {
        // remove the session of the list of managed sessions
        ((BioUdpServer) getService()).destroy(this);
        processSessionClosed();
        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void suspendRead() {
        throw new IllegalStateException("not supported");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void suspendWrite() {
        throw new IllegalStateException("not supported");

    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void resumeRead() {
        throw new IllegalStateException("not supported");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void resumeWrite() {
        throw new IllegalStateException("not supported");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isReadSuspended() {
        return false;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isWriteSuspended() {
        return false;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public IoSessionConfig getConfig() {
        return config;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public WriteRequest enqueueWriteRequest(WriteRequest writeRequest) {

        try {
            int written = ((BioUdpServer) getService()).channel.send((ByteBuffer) writeRequest.getMessage(),
                    remoteAddress);
            if (written > 0) {
                incrementWrittenBytes(written);

                final Object highLevel = ((DefaultWriteRequest) writeRequest).getOriginalMessage();

                if ((highLevel != null) && writeRequest.isConfirmRequested()) {
                    processMessageSent(highLevel);
                }

            } else {
                processException(new RuntimeException("unable to write"));
            }
        } catch (IOException e) {
            processException(e);
        }

        return writeRequest;

    }
}
